(function ($) {
    /**
     * 表格查询
     * @param cols
     * @param rows
     */
    $.fn.table = function (cols, rows) {
        var that = this;
        var url = $(that).attr("data-url");
        if (!url) {
            layer.msg("请配置数据请求链接data-url地址！");
            return;
        }
        var params = {};
        params.ishascheck = $(that).attr("ishascheck");
        $.post(url, {}, function (data) {
            Drawtable(that, data.cols, data.rows, params);
        });

    }
    /**
     * 表格树列表
     * @param cols
     * @param rows
     */
    $.fn.tabletree = function (func) {
        var that = this;
        var url = $(that).attr("data-url");
        if (!url) {
            layer.msg("请配置数据请求链接data-url地址！");
            return;
        }
        var params = {};
        params.ishascheck = $(that).attr("ishascheck");
        $.post(url, {}, function (data) {
            DrawtableTree(that, data.cols, data.rows, params);
            $(that).treegrid({
                expanderExpandedClass: 'glyphicon glyphicon-minus',
                expanderCollapsedClass: 'glyphicon glyphicon-plus'
            });
            func();
        });

    }
    /**
     * 表格分页插件
     * @param pagecount
     */
    $.fn.tablepage = function (pagesets) {
        if (!pagesets || !(pagesets instanceof Object)) {
            pagesets = {};
            pagesets.pageCount = 10;
            pagesets.searchparams = {};
        }

        var that = this;
        var url = $(that).attr("data-url");
        if (!url) {
            layer.msg("请配置数据请求链接data-url地址！");
            return;
        }

        var params = {};
        params.ishascheck = $(that).attr("ishascheck");
        var totalrow = 0;
        var totalpage = 0;
        var searchparams = pagesets.searchparams;
        if (!searchparams) {
            searchparams = {};
        }
        pagesets.curPage = 1;
        $.post(url, searchparams, function (data) {
            totalrow = data.rowsCount;
            totalpage = data.pageCount;
            Drawtable(that, data.cols, data.rows, params);
            var pageinfo = $("<div></div>").css({"float": "left", "margin": "4px 0px", "margin-left": "10px"});
            var layerpage = $("<div></div>").css({"float": "right", "margin-right": "1px"});
            var page = $("<div></div>").addClass("_pagebur").append(pageinfo).append(layerpage);
            $(that).next("._pagebur").remove();
            $(that).after(page);
            laypage({
                cont: layerpage, //分页容器的id
                pages: totalpage, //总页数
                skip: true,
                first: 1, //将首页显示为数字1,。若不显示，设置false即可
                last: totalpage, //将尾页显示为总页数。若不显示，设置false即可
                prev: '<', //若不显示，设置false即可
                next: '>' //若不显示，设置false即可
                , jump: function (obj, first) {
                    pageinfo.html("共" + totalrow + "条记录,共" + obj.pages + "页,当前第" + obj.curr + "页");
                    if (!first) {
                        pagesets.curPage = obj.curr;
                        $.post(url, searchparams, function (data) {
                            Drawtable(that, data.cols, data.rows, params);
                        });
                    }


                }
            });
        });
        // Drawtable(that,cols,rows)

    }
    /*获取table选中的行json数据*/
    $.fn.getTableSelects = function () {
        var selectsRows = [];
        var i = 0;
        $(this).find(".rowcheck:checked").each(function () {
            var rowstr = $(this).parent("td").parent("tr").data("rowdata");
            if (rowstr) {
                selectsRows[i] = rowstr;
                i++;
            }
        });
        return selectsRows;
    };
    /*获取form数据*/
    $.fn.getFormData = function () {
        var data = {};
        $(this).serializeArray().map(function (x) {
            data[x.name] = x.value;
        });
        return data;
    };
    /*设置form数据*/
    $.fn.setFormData = function (row) {
        $(this).find("input").each(function () {
            var name = $(this).attr("name");
            $(this).val(row[name]);
        });
        $(this).find("select").each(function () {
            var name = $(this).attr("name");
            $(this).val(row[name]);
        });
    };
    /*重置表单*/
    $.fn.reset = function () {
        var id = $(this).attr("id");
        document.getElementById(id).reset();
    }
    /**
     * 列表展示插件
     * @param rows
     */
    $.fn.listData = function (rows_,handles_) {
        var rows=rows_||[];
        var handles=handles||{};
        var uldom = $("<ul></ul>").addClass("list-group");
        rows.forEach(function (row, index, array) {
            // var adddom = $("<i class='fa fa-plus' title='新增'></i>").css({"margin-right":"4px","cursor":"pointer"}).click(function (event) {
            //     event.stopPropagation()
            //     var addfunction=handles["add"];
            //     if(addfunction){
            //         eval(addfunction);
            //     }else {
            //         alert("请定义新增方法！");
            //     }
            // });
            var deldom = $("<i class='fa fa-trash' title='删除'></i>").css({"margin-right":"4px","cursor":"pointer"}).click(function (event) {
                event.stopPropagation();
                var addfunction=handles["del"];
                if(addfunction){

                    eval(addfunction);
                }else{
                    alert("请定义删除回调方法！");
                }
                $(this).parent().parent().remove();
            });
            var updatedom = $("<i class='fa fa-edit' title='编辑'></i>").css({"margin-right":"4px","cursor":"pointer"}).click(function (event) {
                event.stopPropagation()
                var addfunction=handles["upd"];
                if(addfunction){
                    eval(addfunction);
                }else{
                    alert("请定义修改回调方法！");
                }
            });
            var handledom = $("<div></div>").addClass("pull-right").append(updatedom).append(deldom);
            $("<a></a>").addClass("list-group-item").css({
                "cursor": "default",
                "padding": "5px 15px"
            }).data("value", row.value).text(row.name).click(function () {
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                } else {
                    $(this).siblings().removeClass("active");
                    $(this).addClass("active");
                    uldom.data("selectvalue", $(this).data("value"));
                }

            }).append(handledom).appendTo(uldom);
        });
        $(this).html("").append(uldom);
        $(this).children("ul").children("a").first().click();
    }
    /**
     * 获取列表选择的值
     */
    $.fn.getListSelectData = function () {
        return $(this).children("ul").data("selectvalue");
    }
    /**
     * 表格绘制
     * that 表格对象本身this
     * cols 列设置
     * rows 行数据
     * */
    function Drawtable(that, cols, rows, params) {
        $(that).addClass("table table-bordered table-hover");
        $(that).css({"margin-bottom": "10px", "font-size": "12px", "text-align": "left"});
        // var htrdom=$("<tr></tr>").css({"background-color":"#F2F2F2"});
        var htrdom = $("<tr></tr>");
        var checkalldom = $("<input type='checkbox'>").bind("change", function () {
            $(this).parents('tr').siblings().find('input.rowcheck').prop("checked", $(this).is(':checked'));
        });
        if (!params) {
            params = {};
        }
        var ishascheck = params.ishascheck;//表格设置是否需要复选框
        if (ishascheck == "true") {
            $("<th></th>").css({"width": "50px", "text-align": "left"}).append(checkalldom).appendTo(htrdom)
        }
        cols.forEach(function (col, index, array) {
            $("<th></th>").css({"width": col.width, "text-align": "left"}).html(col.name).appendTo(htrdom);
        });

        var tbodydom = $("<tbody></tbody>").append(htrdom);
        rows.forEach(function (row, index, array) {
            var tbodytrdom = $("<tr></tr>")
            tbodytrdom.data("rowdata", row);
            if (ishascheck == "true") {
                $("<td></td>").css({
                    "width": "50px",
                    "text-align": "left"
                }).append("<input type='checkbox' class='minimal rowcheck'>").appendTo(tbodytrdom);
            }
            cols.forEach(function (col, index, array) {
                var value = row[col.field]
                if (col.render) {
                    var func = eval(col.render);
                    var e = {};
                    e.value = value;
                    e.index = index;
                    e.row = row;
                    func(e);
                    value = e.value;
                }
                $("<td></td>").html(value).appendTo(tbodytrdom);
            });
            tbodytrdom.click(function () {
                if ($(this).hasClass("active")) {
                    return;
                }
                $(this).siblings().removeClass("active");
                $(this).addClass("active");
                //有复选框才去操作
                if (ishascheck == "true") {
                    $(this).find(".rowcheck").attr("checked","true");
                    $(this).siblings().find(".rowcheck").removeAttr("checked");
                }
                if(params.onRowClick){
                    eval(params.onRowClick);
                }
            });
            tbodydom.append(tbodytrdom);
        })
        $(that).html("");
        $(that).append(tbodydom);
    }
    /**
     * 表格绘制
     * that 表格对象本身this
     * cols 列设置
     * rows 行数据
     * */
    function DrawtableTree(that, cols, rows, params) {
        $(that).addClass("table table-bordered table-striped table-condensed");
        $(that).css({"margin-bottom": "10px", "font-size": "12px", "text-align": "left"});
        // var htrdom=$("<tr></tr>").css({"background-color":"#F2F2F2"});
        var htrdom = $("<tr></tr>");
        var checkalldom = $("<input type='checkbox'>").bind("change", function () {
            $(this).parents('tr').siblings().find('input.rowcheck').prop("checked", $(this).is(':checked'));
        });
        if (!params) {
            params = {};
        }
        var ishascheck = params.ishascheck;//表格设置是否需要复选框
        if (ishascheck == "true") {
            $("<th></th>").css({"width": "50px", "text-align": "left"}).append(checkalldom).appendTo(htrdom)
        }
        cols.forEach(function (col, index, array) {
            $("<th></th>").css({"width": col.width, "text-align": "left"}).html(col.name).appendTo(htrdom);
        });

        var tbodydom = $("<tbody></tbody>").append(htrdom);
        rows.forEach(function (row, index, array) {
            var tbodytrdom = $("<tr></tr>")
            tbodytrdom.addClass("treegrid-"+row.id);
            if(row.pid!=-1){
                tbodytrdom.addClass("treegrid-parent-"+row.pid);
            }
            tbodytrdom.data("rowdata", row);
            if (ishascheck == "true") {
                $("<td></td>").css({
                    "width": "50px",
                    "text-align": "left"
                }).append("<input type='checkbox' class='minimal rowcheck'>").appendTo(tbodytrdom);
            }
            cols.forEach(function (col, index, array) {
                var value = row[col.field]
                if (col.render) {
                    var func = eval(col.render);
                    var e = {};
                    e.value = value;
                    e.index = index;
                    e.row = row;
                    func(e);
                    value = e.value;
                }
                $("<td></td>").html(value).appendTo(tbodytrdom);
            });
            tbodydom.append(tbodytrdom);
        })
        $(that).html("");
        $(that).append(tbodydom);
    }
})(jQuery)